<template>
  <main>
    <div class="main">
      <!-- 标题 -->
      <header>
        <span>标题：</span>
        <input type="text" v-model="passageParams.title" placeholder="请输入标题">
        <span class="date">{{ new Date().getFullYear() + '/' + new Date().getMonth() + '/' + new Date().getDate()
          }}</span>
      </header>
      <!-- 编辑器 -->
      <div class="editor">
        <Toolbar style="border-bottom: .0167rem solid #ccc;" :editor="editorRef" :defaultConfig="toolbarConfig"
          mode="default" />
        <Editor style="height: 8.3333rem; overflow-y: hidden;font-size: .2333rem;" v-model="passageParams.content"
          :defaultConfig="editorConfig" @onCreated="handleCreated" />
      </div>
      <div class="check">
        <div class="label">
          <span>标签：</span>
          <div class="plusLabel" @click="modelVisible = !modelVisible; getTags()">{{
            (passageParams.tag != "") ? '#' + passageParams.tag : '添加标签' }}</div>
        </div>
        <div class="class">
          <span>分类：</span>
          <Select :list="classList" v-model="passageParams.category"></Select>
        </div>
      </div>
      <footer @click="postArticle">
        发布
      </footer>
    </div>
    <div v-show="modelVisible">
      <ModelDialog class="labelDialog">
        <template #header>
          选择标签
        </template>
        <template #body>
          <ul class="tags">
            <li class="newTag">
              <input type="text" placeholder="请输入标签" v-model="passageParams.tag" />
              <div class="new" @click="modelVisible = !modelVisible">新增</div>
            </li>
            <li v-for=" (item, index) in tagList" :key="index" @click="passageParams.tag = item"
              :class="{ 'chosen': item == passageParams.tag }">
              {{ item }}
            </li>
          </ul>
        </template>
        <template #footer>
          <div class="btn" @click="modelVisible = !modelVisible">取消</div>
          <div class="btn" @click="modelVisible = !modelVisible">确定</div>
        </template>
      </ModelDialog>
    </div>
    <ModelDialog class="labelDialog" v-show="success">
      <template #body>
        <br>
        发布成功(点确认跳转)
      </template>
      <template #footer>
        <div class="btn" @click="router.push('/viewpassage/' + newPassageId)">
          确认
        </div>
      </template>
    </ModelDialog>
  </main>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted, reactive } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { reqGetPassageById, reqPostPassage } from '@/apis/passage';
import userStore from '@/stores/modules/user';
import ModelDialog from '@/components/ModelDialog.vue';
import Select from '@/components/Select.vue';
import { reqGetAllTags } from '@/apis/tag';
import { GET_USERID } from '@/utils/tokenAndId';
import { useRoute, useRouter } from 'vue-router';

const route = useRoute()
const router = useRouter()
let modelVisible = ref(false)
let tagList = ref([])
let success = ref(false)
let classList = ref(['生活记录', '技术知识', '文化艺术', '商业财经', '教育学习', '情感心理'])
let newPassageId = ref()// 文章相关属性
const passageParams = reactive({
  id: 0,
  poster_id: userStore().userId,
  title: "",
  content: '',
  category: '请选择',
  tag: "",
  permission: 0, // 0 公开 1 私密
})

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 工具栏配置
const toolbarConfig = {
  excludeKeys: ["group-video", "fullScreen", "group-image"]
}

// 编辑器配置
const editorConfig = {
  placeholder: '请输入内容...'
}



onMounted(() => {
  if (route.path.startsWith('/editpassage')) {
    getPassageById(route.params.id)
  }
})

//通过ID获取文章
const getPassageById = async (id) => {
  let res = await reqGetPassageById(id)
  if (res.code == 200) {
    passageParams.id = res.data.id
    passageParams.title = res.data.title
    passageParams.content = res.data.content
    passageParams.category = res.data.category
    passageParams.tag = res.data.tags
  } else {
    console.log(res);
  }
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

// 发布文章
const postArticle = async () => {
  if (passageParams.title == '') {
    alert('请输入标题')
    return
  }
  if (passageParams.content == '<p><br></p>') {
    alert('请输入内容')
    return
  }
  if (passageParams.category == '请选择') {
    alert('请选择分类')
    return
  }
  if (passageParams.tag == '') {
    alert('请选择标签')
    return
  }
  let res = await reqPostPassage(passageParams)
  if (res.code == 200) {
    console.log(res);
    newPassageId.value = res.data
    success.value = true
  } else {
    console.log(res);
  }
}

// 获取所有标签
const getTags = async () => {
  let res = await reqGetAllTags({ userId: GET_USERID() })
  if (res.code == 200) {
    tagList.value = res.data
  } else {
    console.log(res);
  }
}
</script>

<style scoped lang="scss">
main {
  width: 90%;
  margin: .3333rem auto;
  background-color: #faf1e1;
  padding: .166rem.333rem 0;
  position: relative;

  // 标题
  header {
    display: flex;
    align-items: end;
    margin-bottom: .3333rem;
    font-size: .5rem;

    input {
      background-color: transparent;
      padding-left: .1667rem;
      border: none;
      border-bottom: .0167rem solid #666;
      width: 80%;
      font-size: .45rem;
    }

    .date {
      margin-left: auto;
      font-size: .3333rem;
    }
  }

  .check {
    display: flex;
    align-items: center;
    gap: .333rem;
    margin: .1667rem 0;
    font-size: .3rem;

    .label {
      display: flex;
      align-items: center;

      .plusLabel {
        background-color: #fff;
        border-radius: .5rem;
        padding: .0833rem .1667rem;
        font-size: .28rem;
        color: #A65353;
        cursor: pointer
      }
    }

    .class {
      display: flex;
      align-items: center;
      width: 50%;
    }
  }

  .editor {
    height: 8.3333rem;
    overflow-y: hidden;
  }

  .labelDialog {
    .tags {
      height: 4rem;
      overflow: auto;

      //滚动条样式
      &::-webkit-scrollbar {
        width: 0.1rem;
        height: 0.1rem;
      }

      &::-webkit-scrollbar-thumb {
        background-color: #ccc;
        border-radius: 0.1rem;
      }

      &::-webkit-scrollbar-track {
        background-color: #f5f5f5;
        border-radius: 0.1rem;
      }

      li {
        padding: .05rem;
        cursor: pointer;

        &:hover {
          background-color: #e0e0f0;
          color: #000
        }
      }

      .newTag {
        display: flex;
        justify-content: space-around;
        align-items: center;

        input {
          width: 70%;
        }

        .new {
          background-color: #8F7B3F;
          padding: .05rem;
          border-radius: .05rem;
          color: #fff;
        }
      }
    }

    .btn {
      background-color: #bfb830;
      margin-left: .3333rem;
      border-radius: 20%;
      padding: .0833rem;
      color: #fff;
      cursor: pointer;
    }
  }


  footer {
    display: inline-block;
    float: right;
    box-sizing: border-box;
    background-color: #883c10;
    margin: .0833rem;
    border-radius: .25rem;
    padding: .1333rem;
    font-size: .5rem;
    text-align: center;
    color: #fff;
    cursor: pointer;
  }

  &::after {
    content: '';
    display: block;
    clear: both;
  }

  .labelDialog {
    .btn {
      background-color: #bfb830;
      border-radius: 20%;
      padding: .0833rem;
      color: #fff;
    }

    .chosen {
      background-color: #9F7450;
      color: #fff
    }
  }
}
</style>